package com.cupdata.zicon.jdk7concurrent.chapter2;



import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;



public class ModifyLockfairnessTest {

	//@Test
	public static void main(String[] args) {
		PrintQueue1 printQueue = new PrintQueue1();

		Thread thread[] = new Thread[10];
		for (int i = 0; i < 10; i++) {
			thread[i] = new Thread(new Job1(printQueue), "Thread " + i);
		}

		for (int i=0; i<10; i++){
			thread[i].start();
			try {
			Thread.sleep(100);
			} catch (InterruptedException e) {
			e.printStackTrace();
			}
			}
	}

}

class PrintQueue1 {
	private final Lock queueLock = new ReentrantLock(true);

	public void printJob(Object document) {
		queueLock.lock();
		try {
		Long duration=(long)(Math.random()*10000);
		System.out.println(Thread.currentThread().getName()+":"+
		"PrintQueue: Printing a Job during "+(duration/1000)+" seconds");
		Thread.sleep(duration);
		} catch (InterruptedException e) {
		e.printStackTrace();
		} finally {
		queueLock.unlock();
		}
		
		queueLock.lock();
		try {
		Long duration=(long)(Math.random()*10000);
		System.out.println(Thread.currentThread().getName()+":"+
		"PrintQueue: Printing a Job during "+(duration/1000)+" seconds");
		Thread.sleep(duration);
		} catch (InterruptedException e) {
		e.printStackTrace();
		} finally {
		queueLock.unlock();
		}
	}
}

class Job1 implements Runnable {
	private PrintQueue1 printQueue;

	public Job1(PrintQueue1 printQueue) {
		this.printQueue = printQueue;
	}

	@Override
	public void run() {
		System.out.printf("%s: Going to print a document\n", Thread
				.currentThread().getName());
		printQueue.printJob(new Object());
		System.out.printf("%s: The document has been printed\n", Thread
				.currentThread().getName());
	}
}


